﻿using NLog;
using ServerMonitor.redisHelper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ServerMonitor
{
    class MonitorWorker
    {
        private bool terminate = false;
        private List<DeviceBean> worklist;
        private int timeGap;
        private Dictionary<DeviceBean, WMIService> deviceBeanCoupler = new Dictionary<DeviceBean, WMIService>();
        private static ILogger logger = LogManager.GetCurrentClassLogger();
        public RedisHelper redisHelper;

        public void run()
        {
            Thread.Sleep(5000);//休眠5秒后启动线程，防止大量MS连接未连接成功
            if (worklist.Count < 1)
            {
                //worklist为空时，终止标志为true
                terminate = true;
            }
            logger.Info("MonitorWorker start>>>>>>>>>>>");
            try
            {
                while (!terminate)
                {
                    foreach (DeviceBean deviceBean in worklist)
                    {
                        WMIService wmiService = deviceBeanCoupler[deviceBean];
                        if (wmiService.Ms.IsConnected || wmiService.LocalConnection) //判断MS是否已连接
                        {
                            wmiService.processDeviceBeanData(deviceBean);
                        }
                        else
                        {
                            wmiService.connect();
                            //deviceBean.IsConnected = false; 不以WMI连接情况作为网络通断判定依据
                            deviceBean.UpdateTime = DateTime.Now.ToString();
                        }
                        deviceBean.IsConnected = PingService.TestNetConnectity(deviceBean.IpAddress);
                        redisHelper.HashSet("device_status",deviceBean.DeviceName,deviceBean);
                    }
                    Thread.Sleep(30 * 1000); //休眠
                }
            }
            catch (Exception ex)
            {
                logger.Error("exception in monitor worker:{}",ex.StackTrace.ToString());
            }
            finally {
                if (!terminate)//休眠2秒后重启线程
                {
                    Thread.Sleep(2000);
                    try
                    {
                        Thread.CurrentThread.Abort();
                    }
                    catch (Exception)
                    {

                    }
                    logger.Info("restart monitor worker thread:current thread status:{}", Thread.CurrentThread.ThreadState);
                    new Thread(this.run).Start();
                }
                else {
                    logger.Info("monitor worker terminate flag is true,exit thread");
                }
            }
            
        }

        public void init()
        {
            logger.Info("MonitorWorker init>worklist size:{}", worklist.Count);
            foreach (DeviceBean deviceBean in worklist)
            {
                WMIService wmiService = new WMIService(deviceBean.IpAddress, deviceBean.UserName, deviceBean.Password);
                wmiService.connect();
                deviceBeanCoupler.Add(deviceBean, wmiService);
            }
            redisHelper = new RedisHelper();
        }

        public bool Terminate
        {
            get
            {
                return terminate;
            }

            set
            {
                terminate = value;
            }
        }

        public List<DeviceBean> Worklist
        {
            get
            {
                return worklist;
            }

            set
            {
                worklist = value;
            }
        }




    }
}
